package com.java.netty.common.pptp;

import io.netty.buffer.ByteBuf;

import java.io.Serializable;


public class Packet implements Serializable {
    public static final int PACKET_MIN_LEN = 6;
    public static final int PACKET_DATA_MAX_LEN = 4096;
    /**
     * 命令
     */
    public int cmd;
    /**
     * 协议版本
     */
    public int protocolVer;
    /**
     * 待命时间
     */
    public short onCallTime;
    /**
     * 消息长度
     */
    public int msgLen;
    /**
     * 消息
     */
    public byte[] data;

    public static Packet decodePacket(Packet packetBase, ByteBuf in) {
        packetBase.cmd = in.readByte();
        packetBase.cmd = packetBase.cmd >> 2;
        packetBase.protocolVer = in.readByte();
        packetBase.onCallTime = (short) byte2Int(in.readByte(), in.readByte());
        packetBase.msgLen = byte2Int(in.readByte(), in.readByte());
        if (packetBase.msgLen < PACKET_DATA_MAX_LEN) {
            in.readBytes(packetBase.data = new byte[packetBase.msgLen]);
        } else {
            return null;
        }
        return packetBase;
    }

    public static int byte2Int(byte b1, byte b2) {
        int value;
        value = (int) ((b2 & 0xFF)
                | (b1 & 0xFF) << 8);
        return value;
    }
}
